package com.aduerr.v1shouyin.mvp.activity;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.RemoveRistEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.receiver.WordstoVoice;
import com.aduerr.v1shouyin.util.DownloadUtil;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.orhanobut.hawk.Hawk;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class SettingActivity extends AppCompatActivity {

    public static final String TAG = "SettingActivity";

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.cb_voice_open)
    CheckBox cbVoiceOpen;
    @BindView(R.id.tv_device_id)
    TextView tvDeviceId;
    @BindView(R.id.rl_pos_setting)
    RelativeLayout rlPosSetting;
    @BindView(R.id.tv_update)
    TextView tvUpdate;

    private static AlertDialog showVersionDialog;
    private String version;
    private String versionUrl;
    private Handler updateHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    tvUpdate.setText("已是最新版本");
                    break;
                case 1:
                    tvUpdate.setText("有新版本");
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private DownloadCompleteBroadcast downloadCompleteBroadcast;
    SweetAlertDialog pDialog;
    // 需要点击几次 就设置几
    long[] mHits = new long[7];
    private WordstoVoice voice;
    private AudioManager audioManager;
    private String[] printsettings = new String[]{"不打印", "1张", "2张"};
    private int printpage = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        tvTitle.setText("设置");
        initprintsetting();
        initversionDate();

        downloadCompleteBroadcast = new DownloadCompleteBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(downloadCompleteBroadcast,intentFilter);

        checkVersion();
    }

    private void initprintsetting() {
        printpage = (int) SharedPreferencesUtils.getParam(SettingActivity.this,
                "printpage", 1);
        voice = new WordstoVoice();
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
    }


    //版本信息
    private void initversionDate() {
        PackageManager packageManager = this.getPackageManager();
        try {
            PackageInfo packageInfo =
                    packageManager.getPackageInfo(this.getPackageName(), 0);
            String versionName = packageInfo.versionName;
            tvVersion.setText(versionName);
        } catch(PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        SharedPreferences sp = App.getApp().getSharedPreferences("autovocie",
                Context.MODE_PRIVATE);
        boolean isauto = sp.getBoolean("ischeck", false);
        cbVoiceOpen.setChecked(isauto);
        tvDeviceId.setText(Hawk.get("DeviceID"));
    }


    @OnClick({R.id.img_back, R.id.rl_shop_info, R.id.rl_page_num, R.id.rl_mode,
            R.id.cb_voice_open, R.id.bt_clear, R.id.rl_update, R.id.rl_pos_setting,
            R.id.rl_union_set})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.rl_page_num:
                startActivity(new Intent(SettingActivity.this,
                        PageNumSettingActivity.class));
                break;
            case R.id.rl_shop_info:
                startActivity(new Intent(SettingActivity.this, ShopInfoActivity.class));
                break;
            case R.id.rl_mode:
                startActivity(new Intent(SettingActivity.this, ShiftDutyActivity.class));
                break;
            case R.id.cb_voice_open:
                if(cbVoiceOpen.isChecked()) {
                    voice.toVoice(this, "支付宝成功收款5元");
                    SharedPreferencesUtils.saveYUYINData(this, "ischeck", true);
                } else {
                    SharedPreferencesUtils.saveYUYINData(this, "ischeck", false);
                    audioManager.setRingerMode(android.media.AudioManager.RINGER_MODE_SILENT);
                }
                break;
            case R.id.bt_clear:
                removeRiskManagement();
                break;
            case R.id.rl_pos_setting:
                Intent intent =
                        new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
                startActivity(intent);
                break;
            case R.id.rl_update:
                if(version == null || versionUrl == null) return;
                if(tvUpdate.getText().toString().equals("有新版本")) {
                    showNewVersionDialog();
                }
                break;

            case R.id.rl_union_set:
                Intent intent1 =
                        new Intent(App.getApp(), UnionSettingActivity.class);
                startActivity(intent1);
                break;
        }
    }

    public void showNewVersionDialog() {
        if (showVersionDialog != null && showVersionDialog.isShowing()) {
            showVersionDialog.dismiss();
        }
        TextView msg = new TextView(this);
        msg.setText(String.format("发现新版本V" + version + "，是否立即更新"));
        msg.setPadding(10, 10, 10, 10);
        msg.setGravity(Gravity.CENTER);
        msg.setTextSize(17);
        showVersionDialog = new AlertDialog.Builder(this)
                .setTitle("版本更新")
                .setView(msg)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setCancelable(false)
                .setPositiveButton("稍后再说", (DialogInterface dialog, int which) -> {
                    showVersionDialog.dismiss();
                })
                .setNegativeButton("立即下载", (DialogInterface dialog, int which) -> {
                    new DownloadUtil.Builder(SettingActivity.this)
                            .addUrl(versionUrl)
                            .isWiFi(true)
                            .addDownLoadName(getString(R.string.app_name))
                            .addDscription("开始下载")
                            .builder();
                    showVersionDialog.dismiss();
                }).show();

    }


    /**
     * 解除风控
     */
    private void removeRiskManagement() {
        HashMap<String, String> addParams = new HashMap<>();
        APIRetrofit.getAPIService().removeRiskManagement(RXRequest.getXingPosParams(addParams, SettingActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RemoveRistEntity>() {
                    @Override
                    public void onSubscribe(Disposable disposable) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(SettingActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("请稍等...");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }
                    }

                    @Override
                    public void onNext(RemoveRistEntity removeRistEntity) {
                        int success = removeRistEntity.getSuccess();
                        if(success == 1) {
                            com.blankj.utilcode.util.ToastUtils.showShortSafe("清理成功");
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        if(pDialog != null) {
                            pDialog.dismiss();
                            pDialog = null;
                        }
                    }

                    @Override
                    public void onComplete() {
                        if(pDialog != null) {
                            pDialog.dismiss();
                            pDialog = null;
                        }
                    }
                });
    }


    private void checkVersion() {

        new Thread(() -> {
            String result = null;
            URL url = null;
            HttpURLConnection connection = null;
            InputStreamReader in = null;
            try {
                String paramStr = "";
                url = new URL(Constants.UPDATE_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            JSONObject json = null;
            try {
                json = new JSONObject(result);
                versionUrl = json.optString("url");
                version = json.optString("version");
                int code = json.optInt("code");
                if (code > getPackageManager().getPackageInfo(getPackageName(), 0).versionCode) {
                    updateHandler.sendEmptyMessage(1);
                } else {
                    updateHandler.sendEmptyMessage(0);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch(PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            } catch(Exception e){
                e.printStackTrace();
            }

        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downloadCompleteBroadcast);
    }

    private class DownloadCompleteBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
                DownloadUtil.intallApk(SettingActivity.this, getString(R.string.app_name));
            }
        }
    }
}
